<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button
                type="warning"
                icon="el-icon-download"
                @click="handleExport"
        >导出
        </el-button>
      </template>
      <template #menu-right="{disabled}">
        <div style="float: left; padding-right: 20px;">
          <el-radio-group v-model="query.summaryStatus" class="list">

            <el-radio label=""  @change="refreshChange">全部</el-radio>
            <el-radio label="采购中"  @change="refreshChange">采购中</el-radio>
            <el-radio label="采购已完成"  @change="refreshChange">采购已完成</el-radio>
            <el-radio label="人工关闭"  @change="refreshChange">人工关闭</el-radio>
          </el-radio-group>

        </div>
      </template>
      <template #menu="{ row, size, type }">
        <el-tooltip content="关闭" placement="top">
          <el-button
                  icon="CloseBold"
                  link
                  :size="size"
                  :type="type"
                  @click="() => closeData(row)"
                  v-if="permission.material_summary_close && row.summaryStatus =='采购中'"
          >
          </el-button>
        </el-tooltip>

        <el-tooltip content="撤回" placement="top">
          <el-button
                  icon="RefreshLeft"
                  link
                  :size="size"
                  :type="type"
                  @click="() => backData(row)"
                  v-if="permission.material_summary_close && row.summaryStatus =='人工关闭'"
          >
          </el-button>
        </el-tooltip>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, closeData, backData} from "@/api/anwise/prod/material_summary";
  import {mapGetters} from "vuex";
  import website from '@/config/website';
  import { getToken } from '@/utils/auth';
  import { exportBlob } from '@/api/common';
  import { downloadXls } from '@/utils/util';
  import NProgress from 'nprogress';
  import 'nprogress/nprogress.css';

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
            height:'auto',
            calcHeight: 30,
            tip: false,
            searchShow: false,
            searchMenuSpan: 6,
            border: true,
            index: true,
            selection: false,
            reserveSelection:true,
            labelWidth: 150,
            indexWidth:100,
            menuWidth: 80,
            addBtn: false,
            editBtn: false,
            viewBtn: false,
            delBtn: false,
            stripe: true,
            searchIndex: 3,
            searchIcon: false,
            searchLabelWidth:120,
            searchEnter:true,
            menu:true,
          column: [
            {
              label: "加工商编号",
              prop: "supplierNo",
                type: "number",
                precision:0,
                min:0,
                controls:false,
                search: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "加工商名称",
              prop: "supplierName",
              type: "input",
                search: true,
                overHidden: true,
                sortable: true,
                width:200,
            },
            {
              label: "物料编号",
              prop: "materialNo",
              type: "input",
              search: true,
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "物料名称",
              prop: "materialName",
              type: "input",
              search: true,
                overHidden: true,
                sortable: true,
              width:150,
            },
            {
              label: "规格",
              prop: "specification",
              type: "input",
                overHidden: true,
                sortable: true,
                width:150,
            },
            {
              label: "类别",
              prop: "category",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "单位",
              prop: "unit",
              type: "input",
                overHidden: true,
                sortable: true,
                width:100,
            },
            {
              label: "所需数量",
              prop: "num",
              type: "input",
                overHidden: true,
                sortable: true,
                width:120,
            },
            {
              label: "可采购数量",
              prop: "needNum",
              type: "input",
              overHidden: true,
              sortable: true,
              width:140,
              formatter:(val,value,label)=>{
                  return val.num - val.completeNum
              },
            },
            {
              label: "已采购数量",
              prop: "completeNum",
              type: "input",
                overHidden: true,
                sortable: true,
                width:190,
            },
            {
              label: "状态",
              prop: "summaryStatus",
                type: "select",
                sortable: true,
                overHidden: true,
                filterable:true,
                width: 140,
                dicUrl: '/api/blade-system/dict-biz/dictionary?code=summary_status',
                props: {
                    label: 'dictValue',
                    value: 'dictKey',
                },
                dataType: 'string',
            },
              {
                  label: "关闭人",
                  prop: "closeUser",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:120,
              },
              {
                  label: "关闭时间",
                  prop: "closeTime",
                  type: "input",
                  overHidden: true,
                  sortable: true,
                  width:150,
              },
            {
              label: "箱唛",
              prop: "packLabel",
              type: "input",
              overHidden: true,
              sortable: true,
              width:180,
            },
            {
              label: "箱唛颜色",
              prop: "labelColor",
              type: "input",
              overHidden: true,
              sortable: true,
              width:180,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          viewBtn: this.validData(this.permission.material_summary_view, false),
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleExport(){
        NProgress.start();
        exportBlob(
                `/blade-anwise/prod/material_summary/export?${this.website.tokenHeader
                }=${getToken()}`, this.query
        ).then(res => {
          downloadXls(res.data, `原料采购需求汇总${this.$dayjs().format('YYYYMMDDHHmmss')}.xlsx`);
          NProgress.done();
        });
      },

        backData(row) {
            backData(row.id).then(res => {
          if (res.data.success) {
              this.onLoad(this.page);
              this.$message({
                  type: "success",
                  message: "撤回成功!"
              });
          }
      })
  },
  closeData(row) {
      closeData(row.id).then(res => {
          if (res.data.success) {
              this.onLoad(this.page);
              this.$message({
                  type: "success",
                  message: "关闭成功!"
              });
          }
      })
  },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
